package base;

/**
 * @author aiowang
 * @description:
 * @date 2020/9/21 20:54
 */
public class SyncAndSync {
    public static void main(String[] args) {
        class Count {

            // 含有synchronized同步块的方法
            public void synMethod() {
                synchronized(this) {
                    try {
                        for (int i = 0; i < 5; i++) {
                            Thread.sleep(100); // 休眠100ms
                            System.out.println(Thread.currentThread().getName() + " synMethod loop " + i);
                        }
                    } catch (InterruptedException ie) {
                    }
                }
            }

            // 也包含synchronized同步块的方法
            public void synMethod2() {
                synchronized(this) {
                    try {
                        for (int i = 0; i < 5; i++) {
                            Thread.sleep(100);
                            System.out.println(Thread.currentThread().getName() + " synMethod2 loop " + i);
                        }
                    } catch (InterruptedException ie) {
                    }
                }
            }
        }

        final Count count = new Count();

        // 新建t1, t1会调用“count对象”的synMethod()方法
        Thread t1 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        count.synMethod();
                    }
                }, "t1");

        // 新建t2, t2会调用“count对象”的synMethod2()方法
        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        count.synMethod2();
                    }
                }, "t2");
        t1.start();  // 启动t1
        t2.start();  // 启动t2
    }
}
